package com.heima.a07_demo.server.controller;


import com.heima.a07_demo.common.constant.JwtClaimsConstant;
import com.heima.a07_demo.common.properties.JwtProperties;
import com.heima.a07_demo.common.result.Result;
import com.heima.a07_demo.common.utils.JwtUtil;
import com.heima.a07_demo.pojo.dto.DoctorLoginCodeDTO;
import com.heima.a07_demo.pojo.dto.DoctorLoginDTO;
import com.heima.a07_demo.pojo.entity.Doctor;
import com.heima.a07_demo.pojo.vo.DoctorLoginVO;
import com.heima.a07_demo.server.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/*
* 登陆
* */
@RestController
@RequestMapping("/doctor")
@Slf4j
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/login")
    public Result<DoctorLoginVO> login(@RequestBody DoctorLoginDTO doctorLoginDTO) {
        log.info("员工登录：{}", doctorLoginDTO);

        Doctor doctor=loginService.login(doctorLoginDTO) ;

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.Doctor_ID, doctor.getDoctorId());
        String token = JwtUtil.createJWT(
                jwtProperties.getDoctorSecretKey(),
                jwtProperties.getDoctorTtl(),
                claims);

        DoctorLoginVO doctorLoginVO = DoctorLoginVO.builder()
                .doctorId(doctor.getDoctorId())
                .userName(doctor.getUsername())
                .name(doctor.getName())
                .token(token)
                .build();

        return Result.success(doctorLoginVO);
    }
    @PostMapping("/login/code")
    public Result<DoctorLoginVO> loginByCode(@RequestBody DoctorLoginCodeDTO doctorLoginCodeDTO) {
        log.info("员工验证码登录：{}", doctorLoginCodeDTO);
        Doctor doctor=loginService.loginByCode(doctorLoginCodeDTO) ;
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.Doctor_ID, doctor.getDoctorId());
        String token = JwtUtil.createJWT(
                jwtProperties.getDoctorSecretKey(),
                jwtProperties.getDoctorTtl(),
                claims);

        DoctorLoginVO doctorLoginVO = DoctorLoginVO.builder()
                .doctorId(doctor.getDoctorId())
                .userName(doctor.getUsername())
                .name(doctor.getName())
                .token(token)
                .build();

        return Result.success(doctorLoginVO);
    }
}
